package com.muyu.common.security.utils;

import com.aliyun.cloudauth20190307.Client;
import com.aliyun.cloudauth20190307.models.DescribeFaceVerifyRequest;
import com.aliyun.cloudauth20190307.models.DescribeFaceVerifyResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.muyu.common.core.constant.AlibabaAccessKey;
import com.muyu.common.core.domain.Result;
import com.muyu.common.security.domain.Verify;

import java.util.Arrays;
import java.util.List;

public class DescribeFaceVerify {


    public static void main(String[] args) throws Exception {
        // 示例：调用方法查询认证结果
        String certifyId = "shaa8534cb6912d9fb3bb70b108d913e";
        Result result = describeFaceVerify(certifyId);
        System.out.println(result.toString());
    }

    /**
     * 查询人脸认证信息并输出结果
     * @param certifyId 认证ID
     * @throws Exception
     */
    public static Result describeFaceVerify(String certifyId) throws Exception {
        // 创建请求对象
        DescribeFaceVerifyRequest request = new DescribeFaceVerifyRequest();

        // 设置场景ID和认证ID
        request.setSceneId(Long.valueOf(1000012276));
        request.setCertifyId(certifyId);

        // 推荐，支持服务路由
        DescribeFaceVerifyResponse response = describeFaceVerifyAutoRoute(request);
//        System.out.println(response);
        System.out.println(response.getBody().getResultObject());
//
//        // 打印响应结果
//        System.out.println("Request ID: " + response.getBody().getRequestId());
//        System.out.println("Code: " + response.getBody().getCode());
//        System.out.println("Message: " + response.getBody().getMessage());

        // 处理结果对象信息（避免空指针异常）
        if (response.getBody().getResultObject() != null) {
//            System.out.println("Passed: " + response.getBody().getResultObject().getPassed());
//            System.out.println("SubCode: " + response.getBody().getResultObject().getSubCode());
//            System.out.println("Identity Info: " + response.getBody().getResultObject().getIdentityInfo());
//            System.out.println("Device Token: " + response.getBody().getResultObject().getDeviceToken());
//            System.out.println("Material Info: " + response.getBody().getResultObject().getMaterialInfo());
//            System.out.println(response.getBody().getResultObject().getPassed());
//            String userInfo = response.getBody().getResultObject().getUserInfo();
            System.out.println(response.getBody().getResultObject().getPassed());
            // 解析 JSON 字符串
//            ObjectMapper objectMapper = new ObjectMapper();
//            JsonNode jsonNode = objectMapper.readTree(userInfo);
//
//            // 提取字段
////            String number = jsonNode.get("number").asText();
////            String name = jsonNode.get("name").asText();
////            String verifyName = jsonNode.get("verifyName").asText();
            String passed = response.getBody().getResultObject().getPassed();
//            // 封装为 UserInfo 对象
            Verify user = new Verify(passed);
            return Result.success(user.getPassed(), "通过");
        } else {
           return  Result.error(response.getBody().getResultObject().getPassed(),"认证失败或未获取到认证ID");
        }

    }

    private static DescribeFaceVerifyResponse describeFaceVerifyAutoRoute(DescribeFaceVerifyRequest request) {
        // 第一个为主区域Endpoint，第二个为备区域Endpoint。
        List<String> endpoints = Arrays.asList("cloudauth.cn-shanghai.aliyuncs.com", "cloudauth.cn-beijing.aliyuncs.com");
        DescribeFaceVerifyResponse lastResponse = null;
        for (int i = 0; i < endpoints.size(); i++) {
            try {
                DescribeFaceVerifyResponse response = describeFaceVerify(endpoints.get(i), request);
                lastResponse = response;

                // 服务端错误，切换到下个区域调用。
                if (response != null) {
                    if (500 == response.getStatusCode()) {
                        continue;
                    }
                    if (response.getBody() != null) {
                        if ("500".equals(response.getBody().getCode())) {
                            continue;
                        }
                    }
                }

                return lastResponse;
            } catch (Exception e) {
                if (i == endpoints.size() - 1) {
                    throw new RuntimeException(e);
                }
            }
        }

        return lastResponse;
    }

    private static DescribeFaceVerifyResponse describeFaceVerify(String endpoint, DescribeFaceVerifyRequest request)
            throws Exception {
        // 阿里云账号AccessKey拥有所有API的访问权限，建议您使用RAM用户进行API访问或日常运维。
        // 强烈建议不要把AccessKey ID和AccessKey Secret保存到工程代码里，否则可能导致AccessKey泄露，威胁您账号下所有资源的安全。
        //本示例通过阿里云Credentials工具从环境变量中读取AccessKey，来实现API访问的身份验证。如何配置环境变量，请参见https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();
        Config config = new Config();
        // 设置 AccessKeyId 和 AccessKeySecret
        config.setAccessKeyId(AlibabaAccessKey.ACCESS_KEY_ID);

        config.setAccessKeySecret(AlibabaAccessKey.ACCESS_KEY_SECRET);
        config.setCredential(credentialClient);
        config.setEndpoint(endpoint);
        // 设置http代理。
        //config.setHttpProxy("http://xx.xx.xx.xx:xxxx");
        // 设置https代理。
        //config.setHttpsProxy("http://xx.xx.xx.xx:xxxx");
        Client client = new Client(config);

        // 创建RuntimeObject实例并设置运行参数。
        RuntimeOptions runtime = new RuntimeOptions();
        runtime.readTimeout = 10000;
        runtime.connectTimeout = 10000;

        return client.describeFaceVerifyWithOptions(request, runtime);
    }
}